package cmdline

import (
	"bufio"
	"fmt"
	"mudsv/core"
	"mudsv/core/evt"
	"mudsv/core/sv-main"
	"mudsv/zlog"
	"os"
	"strings"
)

type SvCmd struct {
	Binds map[string]func([]string) //处理列表
}

func NewSvCmd() *SvCmd {
	sv := new(SvCmd)
	sv.Binds = make(map[string]func([]string))
	return sv
}

func (sv *SvCmd) Init() {
	zlog.Info(sv.Name() + " Init")

	core.GetSvCore().EventExecMap[evt.EvTypeCmd] = sv.Exec
}

func (sv *SvCmd) Run() {
	zlog.Info(sv.Name() + " Run")

	for {
		f := bufio.NewReader(os.Stdin) //读取输入的内容
		var msg string
		msg, _ = f.ReadString('\n') //定义一行输入的内容分隔符。
		msg = strings.ReplaceAll(msg, "\r\n", "")
		if len(msg) > 0 && len(msg) < 100 {
			EvtAddCmd(msg)
		}
	}
}

func (sv *SvCmd) Destroy() {
	zlog.Info(sv.Name() + " Destroy")
}

func (sv *SvCmd) Name() string {
	return "SvCmd"
}

func (sv *SvCmd) CmdBind(cmd string, fn func([]string)) {
	sv.Binds[cmd] = fn
}

func (sv *SvCmd) CmdBinds(cs []string, fn func([]string)) {
	for _, v := range cs {
		sv.CmdBind(v, fn)
	}
}

func (sv *SvCmd) Exec(e *evt.Evt) {
	cmd := e.Data.(*CmdInfo)
	fn, ok := sv.Binds[cmd.Cmd]
	if ok {
		fn(cmd.Args)
	} else {
		fmt.Println("无效指令：", cmd)
	}
}

func EvtAddCmd(text string) {
	evt := &evt.Evt{
		Type: evt.EvTypeCmd,
		Data: NewCmdInfo(text),
	}
	sv_main.GetServeMain().EvtChan <- evt
}
